import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-01-13
 * Time: 12:02
 */
class Solution11_1 {
    public boolean wordPattern(String pattern, String s) {
        Map<Character,String> hash1 = new HashMap<Character,String>();
        Map<String,Character> hash2 = new HashMap<String,Character>();
        int count = 0;
        for(int i = 0 ; i < s.length() ; i++){
            if(s.charAt(i) == ' '){
                count++;
            }
        }
        if(pattern.length() != count+1) return false;

        int i = 0 , j = 0 , start = 0 , n = pattern.length() , m = s.length();
        char temp1 = ' ' ; String temp2 = " ";
        while(i < n && j < m && pattern.charAt(i) != ' ' && s.charAt(j) != ' '){
            temp1 = pattern.charAt(i);
            start = j;
            while(s.charAt(j) != ' ' && j < s.length()){
                j++;
            }
            if(j == s.length()-1){
                temp2 = s.substring(start);
            }else{
                temp2 = s.substring(start,j);
            }

            if((hash1.containsKey(temp1) && !hash1.get(temp1).equals(temp2))
                    || (hash2.containsKey(temp2) && !hash2.get(temp2).equals(temp1))){
                return false;
            }
            hash1.put(temp1,temp2);
            i++;
            hash2.put(temp2,temp1);
            j++;
        }
        return true;

    }
}
class Solution11 {
    public boolean wordPattern(String pattern, String s) {
        Map<Character, String> hash1 = new HashMap<>();
        Map<String, Character> hash2 = new HashMap<>();

        // 将字符串 s 按空格分割成单词
        String[] words = s.split(" ");

        // 如果单词数和 pattern 长度不同，直接返回 false
        if (words.length != pattern.length()) {
            return false;
        }

        // 遍历 pattern 和单词数组
        for (int i = 0; i < pattern.length(); i++) {
            char temp1 = pattern.charAt(i);
            String temp2 = words[i];

            // 如果字符 temp1 已经映射到一个不同的单词，或者单词 temp2 已经映射到一个不同的字符，返回 false
            if ((hash1.containsKey(temp1) && !hash1.get(temp1).equals(temp2))
                    || (hash2.containsKey(temp2) && !hash2.get(temp2).equals(temp1))) {
                return false;
            }

            // 更新映射
            hash1.put(temp1, temp2);
            hash2.put(temp2, temp1);
        }

        return true;
    }
}
public class Test11 {

}
